//
//  WebSocketer.swift
//  Extend
//
//  Created by 郑浩 on 2017/10/25.
//  Copyright © 2017年 敬信. All rights reserved.
//

import UIKit
import Starscream

@objc public protocol WebSocketerDelegate {
    ///连接成功
    @objc optional func websocketDidConnect(socket: WebSocketer)
    ///连接失败
    @objc optional func websocketDidDisconnect(socket: WebSocketer, error: Error?)
    ///接受文字信息
    @objc optional func websocketDidReceiveMessage(socket: WebSocketer, text: String)
    ///接受二进制信息
    @objc optional func websocketDidReceiveData(socket: WebSocketer, data: Data)
}

public class WebSocketer: NSObject, WebSocketDelegate {
    
    var socket: WebSocket!
    public var webSocketDelegate: WebSocketerDelegate?
    
    ///单例
    public static let share = WebSocketer()
    private override init() {}
    
    ///链接服务器
    public func connectSever(severUrl: String) {
        socket = WebSocket(url: URL(string: severUrl)!)
        socket.delegate = self
        socket.connect()
    }
    
    ///发送文字消息
    public func sendWord(word: String) {
        if socket != nil {
            socket.write(string: word)
        }
    }
    
    ///发送data
    public func sendData(aData: Data) {
        socket.write(data: aData)
    }
    
    ///断开连接
    public func disconnect() {
        if socket != nil {
            socket.disconnect()
            socket.delegate = nil
            socket = nil
            print("断开webdocket")
        }
    }
    
    //MARK: - WebSocketDelegate
    
    public func websocketDidConnect(socket: WebSocketClient) {
        print("连接成功")
        webSocketDelegate?.websocketDidConnect!(socket: self)
    }
    
    public func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
        print("连接失败了")
        webSocketDelegate?.websocketDidDisconnect!(socket: self, error: error)
    }
    
    public func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
        print("接收到消息：\(text)")
        webSocketDelegate?.websocketDidReceiveMessage!(socket: self, text: text)
    }

    public func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
        print("接受到二进制消息")
        webSocketDelegate?.websocketDidReceiveData!(socket: self, data: data)
    }
}
